const dbDir = getAssets()+'dragonBone/';

function getSkeArmatureAndActions(obj: Object, index: number): [string, string[]] {
	for (const [key, v] of Object.entries(obj)) {
		if (key === 'armature' && Array.isArray(v)) {
			const vv = v[index];
			if (vv.type === 'Armature' && Array.isArray(vv.animation)) {
				const anis = [];
				for (const ani of vv.animation) {
					anis.push(ani.name);
				}
				return [vv.name, anis];
			}
		}
	}
	return [null, null];
}

async function createDB(
	file: string,
	index: number,
	action: string,
): Promise<[dragonBones.EgretArmatureDisplay, string[]]> {
	const skeletonData = await RES.getResByUrl(
		`${dbDir}${file}_ske.json`,
		null,
		null,
		RES.ResourceItem.TYPE_JSON,
	);
	if (!skeletonData) {
		return null;
	}
	const textureData = await RES.getResByUrl(
		`${dbDir}${file}_tex.json`,
		null,
		null,
		RES.ResourceItem.TYPE_JSON,
	);
	if (!textureData) {
		return null;
	}
	const texture = await RES.getResByUrl(
		`${dbDir}${file}_tex.png`,
		null,
		null,
		RES.ResourceItem.TYPE_IMAGE,
	);
	if (!texture) {
		return null;
	}
	const factory = new dragonBones.EgretFactory();
	factory.parseDragonBonesData(skeletonData);
	factory.parseTextureAtlasData(textureData, texture);
	const [ani, anis] = getSkeArmatureAndActions(skeletonData, index);
	if (!ani) {
		return null;
	}
	const db = factory.buildArmatureDisplay(ani);
	if (db && action) {
		action = anis.includes(action) ? action : anis[0];
		db.animation.play(action);
	}
	return [db, anis];
}
